import type { BasicKeys } from '../cache/persistent';
import { Persistent } from '../cache/persistent';
import { ACCESS_TOKEN_KEY, CacheTypeEnum, REFRESH_TOKEN_KEY, TENANT_ID_KEY } from '../../enums/cacheEnum';

const defaultSetting = {
  permissionCacheType: CacheTypeEnum.LOCAL,
};

// 使用本地存储还是Session存储
const isLocal = defaultSetting.permissionCacheType === CacheTypeEnum.LOCAL;

// 添加一个全局变量来跟踪重定向状态
let isRedirecting = false;

export function getAccessToken(): string {
  return getAuthCache(ACCESS_TOKEN_KEY);
}

export function setAccessToken(value: string) {
  return setAuthCache(ACCESS_TOKEN_KEY, value);
}

export function getRefreshToken(): string {
  return getAuthCache(REFRESH_TOKEN_KEY);
}

export function setRefreshToken(value: string) {
  return setAuthCache(REFRESH_TOKEN_KEY, value);
}

export function getTenantId() {
  return getAuthCache(TENANT_ID_KEY);
}

export function setTenantId(value: any) {
  return setAuthCache(TENANT_ID_KEY, value);
}

export function getAuthCache<T>(key: BasicKeys) {
  const fn = isLocal ? Persistent.getLocal : Persistent.getSession;
  return fn(key) as T;
}

export function setAuthCache(key: BasicKeys, value: any) {
  const fn = isLocal ? Persistent.setLocal : Persistent.setSession;
  return fn(key, value, true);
}

export function clearAuthCache(immediate = true) {
  const fn = isLocal ? Persistent.clearLocal : Persistent.clearSession;
  return fn(immediate);
}

/**
 * 检查登录状态并在必要时重定向到登录页
 * @param showMessage 是否显示提示消息，默认为true
 * @returns 返回是否已登录
 */
export function checkAndRedirect(showMessage = true): boolean {
  const token = getAccessToken();

  if (!token) {
    // 如果已经在重定向中，直接返回
    if (isRedirecting) {
      console.log('checkAndRedirect: 已经在重定向过程中，跳过');
      return false;
    }

    console.log('checkAndRedirect: 未检测到有效token，需要重定向');

    if (showMessage) {
      try {
        if (window.ElMessage) {
          window.ElMessage.warning('登录已过期，即将跳转到登录页');
        } else {
          console.warn('登录已过期，即将跳转到登录页');
        }
      } catch (e) {
        console.error('显示消息失败:', e);
      }
    }

    try {
      // 设置重定向状态
      isRedirecting = true;

      // 优先使用 Electron IPC 进行跳转
      if (window.ipcRenderer) {
        console.log('使用 Electron IPC 重定向到登录页');
        window.ipcRenderer.send('redirect-to-login');
        return false;
      }
    } catch (e) {
      console.error('重定向到登录页失败:', e);
      // 重置重定向状态
      isRedirecting = false;
    }

    return false;
  }

  return true;
}

// 添加Window接口扩展，以支持ElMessage
declare global {
  interface Window {
    ElMessage?: {
      warning: (message: string) => void;
      error: (message: string) => void;
      success: (message: string) => void;
    };
    ipcRenderer: Electron.IpcRenderer;
  }
}
